import { useMemberStore } from '@/stores'//引入用户信息携带token
import { getRequestHost } from './host'
const requestBaseUrl = getRequestHost()
const memberStore = useMemberStore()

const httpInterceptor = {  // 请求处理
	invoke(options : UniApp.RequestOptions) {
		options.url = options.url.startsWith('http') ? options.url : requestBaseUrl + options.url
		options.timeout = 10000
		options.header = { ...options.header,  "Authorization": 'Bearer'+ memberStore.profile?.token }
	}
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

type Data<T> = {   // 响应处理
	code : string,
	msg : string,
	data : T,
	status : boolean,
	otherData ?: any
}
export const http = <T>(options : UniApp.RequestOptions) => new Promise<Data<T>>((resolve, reject) => {
	uni.request({
		...options,
		success(res) {
			if (res.statusCode >= 200 && res.statusCode < 300) {
				return resolve(res.data as Data<T>)
			}
			if (res.statusCode == 401) {
				memberStore.clearProfile()
				uni.navigateTo({ url: '/pages/login/login' })
				return reject(res)
			}
			uni.showToast({ icon: 'none', title: (res.data as Data<T>).msg || '请求错误' })
			reject(res)
		},
		fail(err) { 
			uni.showToast({ icon: 'none', title: err.errMsg || '网络错误，换个网络试试' })
			reject(err)
		}
	})
})

// 基于options 做二次封装
export const GET = <T>(url : string, data?: any) => {
	return http<T>({
		method: 'GET',
		url,
		data
	})
}

export const POST = <T>(url : string, data: any) => {
	return http<T>({
		method: 'POST',
		url,
		data
	})
}

export const DELETE = <T>(url : string, data : any) => {
	return http<T>({
		method: 'DELETE',
		url,
		data
	})
}

export const PUT = <T>(url : string, data:any) => {
	return http<T>({
		method: 'PUT',
		url,
		data
	})
}